<?php
namespace app\service;

use app\model\SystemConfig;
use PHPMailer\PHPMailer\PHPMailer;
use think\facade\Log;

class MailService
{
    protected $mailer;
    protected $config;

    public function __construct()
    {
        $this->loadConfig();
        $this->initMailer();
    }

    /**
     * 加载邮件配置
     */
    protected function loadConfig()
    {
        $this->config = [
            'host' => SystemConfig::getConfig('mail_host'),
            'port' => SystemConfig::getConfig('mail_port'),
            'username' => SystemConfig::getConfig('mail_username'),
            'password' => SystemConfig::getConfig('mail_password'),
            'from' => SystemConfig::getConfig('mail_from'),
            'from_name' => SystemConfig::getConfig('mail_from_name'),
            'site_name' => SystemConfig::getConfig('site_name', '知更开放平台'),
            'site_url' => SystemConfig::getConfig('site_url')
        ];
    }

    /**
     * 初始化邮件发送器
     */
    protected function initMailer()
    {
        $this->mailer = new PHPMailer(true);
        $this->mailer->isSMTP();
        $this->mailer->Host = $this->config['host'];
        $this->mailer->SMTPAuth = true;
        $this->mailer->Username = $this->config['username'];
        $this->mailer->Password = $this->config['password'];
        $this->mailer->SMTPSecure = 'ssl';
        $this->mailer->Port = $this->config['port'];
        $this->mailer->CharSet = 'UTF-8';
        $this->mailer->setFrom($this->config['from'], $this->config['from_name']);
    }

    /**
     * 发送验证码邮件
     * @param int $userId 用户ID
     * @param string $email 用户邮箱
     * @param string $code 验证码
     */
    public function sendVerificationCode($userId, $email, $code)
    {
        try {
            $this->mailer->addAddress($email);
            $this->mailer->Subject = "[{$this->config['site_name']}] 邮箱验证码";

            // 生成验证链接，使用user_id而不是email
            $verifyUrl = $this->config['site_url'] . "/user/verify_email?user_id=" . $userId . "&code=" . $code;

            $mailContent = <<<EOT
            <div style="padding: 20px;">
                <h2>您好！</h2>
                <p>您正在验证邮箱，验证码为：</p>
                <div style="background: #f5f7fa; padding: 15px; text-align: center; margin: 20px 0;">
                    <span style="font-size: 24px; font-family: monospace; letter-spacing: 5px; color: #333;">{$code}</span>
                </div>
                
                <div style="text-align: center; margin: 30px 0;">
                    <a href="{$verifyUrl}" 
                       style="display: inline-block; background: #007bff; color: #fff; text-decoration: none; padding: 12px 30px; border-radius: 5px; font-size: 16px;">
                        点击验证邮箱
                    </a>
                </div>
                
                <p>您也可以复制验证码到验证页面完成验证。验证码有效期为24小时，请尽快完成验证。</p>
                
                <div style="background: #fff8e6; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0;">
                    <p style="margin: 0; color: #856404;">
                        ⚠️ 注意：
                        <br>• 验证码有效期为24小时
                        <br>• 请勿将验证码泄露给他人
                        <br>• 如果这不是您的操作，请忽略此邮件
                    </p>
                </div>
                
                <p style="color: #666; margin-top: 20px; font-size: 14px;">
                    此邮件由系统自动发送，请勿回复。<br>
                    <a href="{$this->config['site_url']}" style="color: #007bff; text-decoration: none;">{$this->config['site_name']}</a>
                </p>
            </div>
EOT;

            $this->mailer->isHTML(true);
            $this->mailer->Body = $mailContent;
            $this->mailer->AltBody = strip_tags($mailContent);

            return $this->mailer->send();
        } catch (\Exception $e) {
            Log::error('验证码邮件发送失败：' . $e->getMessage());
            throw new \Exception('邮件发送失败：' . $e->getMessage());
        } finally {
            $this->mailer->clearAddresses();
        }
    }

    /**
     * 发送重置密码邮件
     */
    public function sendResetPasswordEmail($email, $userId, $resetCode)
    {
        try {
            $this->mailer->addAddress($email);
            $this->mailer->Subject = "[{$this->config['site_name']}] 重置密码";

            $resetUrl = $this->config['site_url'] . '/reset_password?user_id=' . $userId . '&code=' . $resetCode;

            $mailContent = <<<EOT
            <div style="background-color: #f5f7fa; padding: 40px 0;">
                <div style="max-width: 600px; margin: 0 auto; background-color: #fff; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); padding: 40px;">
                    <div style="text-align: center; margin-bottom: 30px;">
                        <h2 style="color: #333; margin: 0;">重置密码</h2>
                    </div>
                    
                    <div style="color: #666; font-size: 16px; line-height: 1.6;">
                        <p>您好！</p>
                        <p>我们收到了重置您在 {$this->config['site_name']} 账号密码的请求。</p>
                        <p>您的验证码是：</p>
                        <div style="background: #f5f7fa; padding: 15px; border-radius: 5px; text-align: center; margin: 20px 0;">
                            <span style="font-size: 24px; font-family: monospace; letter-spacing: 5px; color: #333;">{$resetCode}</span>
                        </div>
                        
                        <div style="text-align: center; margin: 30px 0;">
                            <a href="{$resetUrl}" 
                               style="display: inline-block; background: #007bff; color: #fff; text-decoration: none; padding: 12px 30px; border-radius: 5px; font-size: 16px;">
                                重置密码
                            </a>
                        </div>
                        
                        <div style="background: #fff8e6; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0;">
                            <p style="margin: 0; color: #856404;">
                                ⚠️ 注意：
                                <br>• 验证码有效期为24小时
                                <br>• 请勿将验证码泄露给他人
                                <br>• 如果这不是您的操作，请忽略此邮件
                            </p>
                        </div>
                    </div>
                    
                    <div style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee; text-align: center; color: #999; font-size: 14px;">
                        <p>此邮件由系统自动发送，请勿回复</p>
                        <p style="margin: 5px 0;">
                            <a href="{$this->config['site_url']}" style="color: #007bff; text-decoration: none;">{$this->config['site_name']}</a>
                        </p>
                    </div>
                </div>
            </div>
EOT;

            $this->mailer->isHTML(true);
            $this->mailer->Body = $mailContent;
            $this->mailer->AltBody = strip_tags($mailContent);

            return $this->mailer->send();
        } catch (\Exception $e) {
            Log::error('重置密码邮件发送失败：' . $e->getMessage());
            throw new \Exception('邮件发送失败：' . $e->getMessage());
        } finally {
            $this->mailer->clearAddresses();
        }
    }

    /**
     * 发送安全警告邮件
     */
    public function sendSecurityWarningEmail($email, $ip, $isLongLock = false)
    {
        try {
            $this->mailer->addAddress($email);
            $this->mailer->Subject = "[{$this->config['site_name']}] 账号安全警告";

            $lockDuration = $isLongLock ? '24小时' : '30分钟';

            $mailContent = <<<EOT
            <div style="padding: 20px;">
                <h2>安全警告</h2>
                <p>您好，</p>
                <p>我们检测到您的账号存在异常登录尝试：</p>
                <ul>
                    <li>登录邮箱：{$email}</li>
                    <li>登录IP：{$ip}</li>
                    <li>时间：{$this->getCurrentDateTime()}</li>
                </ul>
                <p>由于多次登录失败，您的账号已被临时锁定{$lockDuration}。</p>
                <p>如果这不是您的操作，建议您及时修改密码。</p>
                <div style="margin: 20px 0;">
                    <a href="{$this->config['site_url']}" 
                       style="background: #007bff; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; display: inline-block;">
                       访问系统
                    </a>
                    <a href="{$this->config['site_url']}/user/to_reset_password?email={$email}" 
                       style="background: #28a745; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; display: inline-block; margin-left: 10px;">
                       重置密码
                    </a>
                </div>
                <p>为了账号安全，请注意：</p>
                <ul>
                    <li>不要将密码告诉他人</li>
                    <li>使用复杂的密码组合</li>
                    <li>定期更换密码</li>
                    <li>不要在不安全的设备上登录</li>
                </ul>
                <p style="color: #666; margin-top: 20px;">
                    此邮件由系统自动发送，请勿回复。<br>
                    如有疑问，请访问 <a href="{$this->config['site_url']}" style="color: #007bff;">{$this->config['site_name']}</a>
                </p>
            </div>
EOT;

            $this->mailer->isHTML(true);
            $this->mailer->Body = $mailContent;
            $this->mailer->AltBody = strip_tags($mailContent);

            return $this->mailer->send();
        } catch (\Exception $e) {
            Log::error('安全警告邮件发送失败：' . $e->getMessage());
            throw new \Exception('邮件发送失败：' . $e->getMessage());
        } finally {
            $this->mailer->clearAddresses();
        }
    }

    /**
     * 发送提醒邮件
     */
    public function sendReminderEmail($user, $reminder)
    {
        try {
            $this->mailer->addAddress($user->email);
            $this->mailer->Subject = "[{$this->config['site_name']}] {$reminder->title}";

            // 生成操作链接
            $completeUrl = $this->config['site_url'] . "/reminder/complete_page?reminder_id={$reminder->id}&key={$reminder->operation_key}";
            $postponeUrl = $this->config['site_url'] . "/reminder/postpone_page?reminder_id={$reminder->id}&key={$reminder->operation_key}";
            $noteUrl = $this->config['site_url'] . "/reminder/note_page?reminder_id={$reminder->id}&key={$reminder->operation_key}";

            $mailContent = <<<EOT
            <div style="padding: 20px;">
                <h2>您好，{$user->username}！</h2>
                <p>您设置的提醒事项已到期：</p>
                <div style="background: #f5f5f5; padding: 15px; margin: 10px 0;">
                    <h3 style="margin: 0 0 10px 0;">{$reminder->title}</h3>
                    <p style="margin: 0;">{$reminder->description}</p>
                    <p style="margin: 10px 0 0 0;">提醒时间：{$reminder->due_date}</p>
                </div>
                
                <p>您可以：</p>
                <div style="margin: 20px 0;">
                    <a href="{$completeUrl}" style="background: #4CAF50; color: white; padding: 10px 20px; text-decoration: none; display: inline-block; margin: 0 10px 10px 0;">标记完成</a>
                    <a href="{$postponeUrl}" style="background: #2196F3; color: white; padding: 10px 20px; text-decoration: none; display: inline-block; margin: 0 10px 10px 0;">延后提醒</a>
                    <a href="{$noteUrl}" style="background: #FF9800; color: white; padding: 10px 20px; text-decoration: none; display: inline-block; margin: 0 10px 10px 0;">添加备注</a>
                </div>

                <p style="color: #666; margin-top: 20px; font-size: 14px;">
                    如果这不是您设置的提醒，请忽略此邮件。<br>
                    {$this->config['site_name']}
                </p>
            </div>
EOT;

            $this->mailer->isHTML(true);
            $this->mailer->Body = $mailContent;
            $this->mailer->AltBody = strip_tags($mailContent);

            return $this->mailer->send();
        } catch (\Exception $e) {
            Log::error('提醒邮件发送失败：' . $e->getMessage());
            throw new \Exception('邮件发送失败：' . $e->getMessage());
        } finally {
            $this->mailer->clearAddresses();
        }
    }

    /**
     * 获取当前时间
     */
    protected function getCurrentDateTime()
    {
        return date('Y-m-d H:i:s');
    }
}